define(['jquery'], function ($) {
    var ksspa;

    function KSSPA() {
    }

    KSSPA.prototype.start = function (config) {
        var self = this;
        self.routerMap = config.router;
        self.mainView = config.view;
        self.errorTemplateId = config.errorTemplateId;
        startRouter();
        window.onhashchange = function () {
            startRouter()
        }
    };
    var messageStack = [];
    KSSPA.prototype.getMessage = function (id) {
        var msg = {};
        $.each(messageStack, function (i, e) {
            if (e.id === id) {
                msg = e
            }
        });
        return msg
    };
    KSSPA.prototype.setMessage = function (obj) {
        var _obj = JSON.parse(JSON.stringify(obj));
        $.each(messageStack, function (i, e) {
            if (e.id === _obj.id) {
                e = _obj;
                return false
            }
        });
        messageStack.push(_obj)
    };
    KSSPA.prototype.delMessage = function (id) {
        if (typeof id === 'undefined') {
            return false
        }
        var index = 0;
        $.each(messageStack, function (i, e) {
            if (e.id === id) {
                index = i
            }
        });
        $.each(messageStack, function (i, e) {
            if (i > index) {
                messageStack[i - 1] = e
            }
        })
    };
    KSSPA.prototype.clearMessage = function (id) {
        var index = 0;
        messageStack = []
    };
    KSSPA.prototype.stringify = function (routerUrl, paramObj) {
        var paramStr = '',
            hash;
        for (var i in paramObj) {
            paramStr += i + '=' + encodeURIComponent(paramObj[i]) + '&'
        }
        if (paramStr === '') {
            hash = routerUrl
        } else {
            paramStr = paramStr.substring(0, paramStr.length - 1);
            hash = routerUrl + '?' + paramStr
        }
        return hash
    };
    KSSPA.prototype.parse = function (routerHash) {
// debugger;
        var hash = typeof routerHash === 'undefined' ? location.hash : routerHash;
        var obj = {
            url: '',
            param: {}
        };
        var param = {},
            url = '';
        var pIndex = hash.indexOf('?');
        if (hash === '') {
            return obj
        }
        if (pIndex > -1) {
            url = hash.substring(1, pIndex);
            var paramStr = hash.substring(pIndex + 1);
            var paramArr = paramStr.split('&');
            $.each(paramArr, function (i, e) {
                var item = e.split('='),
                    key, val;
                key = item[0];
                val = item[1];
                if (key !== '') {
                    param[key] = decodeURIComponent(val)
                }
            })
        } else {
            url = hash.substring(1);
            param = {}
        }

        return {
            url: url,
            param: param
        }
    };

    function routerAction(routeObj) {

        // debugger;
        var router_key = routeObj.url;
        var routerItem = ksspa.routerMap[router_key];
        if (typeof routerItem === 'undefined') {
            var defaultRoute = ksspa.routerMap.default;
            routerItem = ksspa.routerMap[defaultRoute];
            location.hash = defaultRoute;
            return false
        }
        // debugger;
        var param_str = '';
        $.each(routeObj.param, function (key, value) {
            param_str += '/' + key + '/' + value
        })

        // debugger;
        var url = routerItem.view;
        if (url.indexOf('.html') > 0) {
            url = url.replace('.html', '');
            url += param_str + '.html'
        } else {
            url += param_str
        }


        // router_key+="-cache";
        // if ($(".ks-no-cache").length > 0) {
        //     $(".ks-no-cache").remove();
        //
        // }
        // if ($(".ks-spa-cache").length > 0) {
        //     $(".ks-spa-cache").hide();
        // }
        if (router_key == 'index') {

            // $(".ks-spa-cache").addClass('addds');
            var u = navigator.userAgent;
            if (!!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
                $("body>header").show();
                $("body>.pages").show();
                $(".ks-spa-cache").hide();
            }
        } else {
            var u = navigator.userAgent;
            if (!!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
                $(".ks-spa").hide();
                $(".ks-spa>div").removeClass('ks-fade-r');

                $("body>.pages").hide();
                $("body>header").hide();
            }
            // router_key=router_key+"-cache"


            // console.log(router_key.indexOf('-cache'));

            // var flag_cache = false;
            // if (router_key.indexOf('-cache') == -1) {
            //     flag_cache = true;
            var cache_id = "#ks-" + router_key;
            if ($(cache_id).length > 0) {
                //$(".ks-spa-cache").hide();
                $(".ks-spa-cache").css('z-index', '');
                $(cache_id).css('z-index', 997).show();
                // $(cache_id).show();
            } else {
                $(".ks-spa-cache").css('z-index', '');
                $(ksspa.mainView).append('<div id="ks-' + router_key + '" class="ks-spa-cache ks-spa" style="position: absolute;top:0;left:0;width: 100%;height:100%;z-index:997;overflow-y: scroll"></div>');
                var obj = $(cache_id);
                loadHtml(obj, url, routerItem, routeObj);
            }
            // } else {
            //     if (router_key != 'index') {
            //         $(".ks-spa-cache").css('z-index', '');
            //         $(ksspa.mainView).append('<div id="ks-' + router_key + '" class="ks-no-cache ks-spa" style="position: absolute;top:0;left:0;width: 100%;height:100%;z-index:9999"></div>');
            //         var obj = $("#ks-" + router_key);
            //         loadHtml(obj, url, routerItem, routeObj.param, flag_cache);
            //     }
            // }
        }

    }


    function loadHtml(obj, url, routerItem, routeObj) {

        $.ajax({
            type: 'GET',
            url: url,
            // async: false,
            dataType: 'json',
            beforeSend: function (xhr, settings) {
                ksspa.showLoading()
            },
            success: function (data, status, xhr) {

                obj.html(data);

                var ksclose = $('.ks-close');
                if (ksclose.length > 0) {
                    ksclose.each(function () {
                        $(this).on('click', function () {
                            // console.log($(this).parents('.ks-spa').html());
                            history.go(-1);
                            $(this).parents('.ks-spa').remove();

                        })
                    })
                }
                //  var ksclose = document.querySelector('.ks-close');
                // if (ksclose) {
                //     ksclose.addEventListener('tap', function () {
                //         // $(".ks-close").parents('header').parent('div').remove();
                //         console.log(this.parentNode);
                //     })
                // }


                //                    $(ksspa.mainView).html(data);
                if (typeof (routerItem.controller) != 'undefined') {
                    // loadScript(routerItem.controller)
                    //$("script[data-requiremodule='"+routerItem.controller+"']").remove()
                    // console.log(obj);

                    // if (!flag_cache) {
                    //     requirejs.undef(routerItem.controller);
                    // }
                    requirejs.undef(routerItem.controller);


                    require([routerItem.controller], function (model) {
                        try {
                            if (typeof(eval(model.init)) == "function") {
                                var routerinfo = {
                                    router_name: routeObj.url,
                                    router_url: routerItem.view,
                                    router_controller: routerItem.controller
                                }
                                param = $.extend(routeObj.param, routerinfo);
                                model.init(param)
                            }
                        } catch (e) {
                        }

                    });


                    // if ($.isEmptyObject(param)) {
                    //     require([routerItem.controller]);
                    // } else {
                    //     require([routerItem.controller], function (model) {
                    //         model.init(param)
                    //     });
                    // }


                }
                obj.show();
                ksspa.hideLoading()
            },
            error: function (xhr, errorType, error) {
                ksspa.hideLoading();
                if ($(ksspa.errorTemplateId).length === 0) {
                    return false
                }
                var errHtml = $(ksspa.errorTemplateId).html();
                errHtml = errHtml.replace(/{{errStatus}}/, xhr.status);
                errHtml = errHtml.replace(/{{errContent}}/, xhr.responseText);
                $(ksspa.mainView).html(errHtml)
            }
        })
    }

    KSSPA.prototype.showLoading=function() {
        var _html = '<div id="ks-loadingToast" class="weui_loading_toast" style="position: absolute; z-index: 99999;"><div id="ks-popup" style="position: fixed;top: 0;left: 0; z-index: 998; width: 100%; height: 100vh; background: rgba(0,0,0,0.4)"></div><div class="weui_mask_transparent"></div><div class="weui_toast"><div class="weui_loading"><div class="weui_loading_leaf weui_loading_leaf_0"></div><div class="weui_loading_leaf weui_loading_leaf_1"></div><div class="weui_loading_leaf weui_loading_leaf_2"></div><div class="weui_loading_leaf weui_loading_leaf_3"></div><div class="weui_loading_leaf weui_loading_leaf_4"></div><div class="weui_loading_leaf weui_loading_leaf_5"></div><div class="weui_loading_leaf weui_loading_leaf_6"></div><div class="weui_loading_leaf weui_loading_leaf_7"></div><div class="weui_loading_leaf weui_loading_leaf_8"></div><div class="weui_loading_leaf weui_loading_leaf_9"></div><div class="weui_loading_leaf weui_loading_leaf_10"></div><div class="weui_loading_leaf weui_loading_leaf_11"></div></div><p class="weui_toast_content">数据加载中</p></div></div>';
        if ($("#ks-loading-style").length > 0) {
        } else {
            var _style = '<style id="ks-loading-style">.weui_toast{position:fixed;z-index:3;width:7.6em;min-height:7.6em;top:180px;left:50%;margin-left:-3.8em;background:rgba(40,40,40,.75);text-align:center;border-radius:5px;color:#FFF}.weui_icon_toast{margin:22px 0 0;display:block}.weui_icon_toast:before{content:"EA08";color:#FFF;font-size:55px}.weui_toast_content{margin:0 0 15px}.weui_loading_toast .weui_toast_content{margin-top:64%;font-size:14px}.weui_loading{position:absolute;width:0;z-index:2000000000;left:50%;top:38%}.weui_loading_leaf{position:absolute;top:-1px;opacity:.25}.weui_loading_leaf:before{content:" ";position:absolute;width:8.14px;height:3.08px;background:#d1d1d5;box-shadow:rgba(0,0,0,.0980392) 0 0 1px;border-radius:1px;-webkit-transform-origin:left 50% 0;transform-origin:left 50% 0}.weui_loading_leaf_0{-webkit-animation:opacity-60-25-0-12 1.25s linear infinite;animation:opacity-60-25-0-12 1.25s linear infinite}.weui_loading_leaf_0:before{-webkit-transform:rotate(0) translate(7.92px,0);transform:rotate(0) translate(7.92px,0)}.weui_loading_leaf_1{-webkit-animation:opacity-60-25-1-12 1.25s linear infinite;animation:opacity-60-25-1-12 1.25s linear infinite}.weui_loading_leaf_1:before{-webkit-transform:rotate(30deg) translate(7.92px,0);transform:rotate(30deg) translate(7.92px,0)}.weui_loading_leaf_2{-webkit-animation:opacity-60-25-2-12 1.25s linear infinite;animation:opacity-60-25-2-12 1.25s linear infinite}.weui_loading_leaf_2:before{-webkit-transform:rotate(60deg) translate(7.92px,0);transform:rotate(60deg) translate(7.92px,0)}.weui_loading_leaf_3{-webkit-animation:opacity-60-25-3-12 1.25s linear infinite;animation:opacity-60-25-3-12 1.25s linear infinite}.weui_loading_leaf_3:before{-webkit-transform:rotate(90deg) translate(7.92px,0);transform:rotate(90deg) translate(7.92px,0)}.weui_loading_leaf_4{-webkit-animation:opacity-60-25-4-12 1.25s linear infinite;animation:opacity-60-25-4-12 1.25s linear infinite}.weui_loading_leaf_4:before{-webkit-transform:rotate(120deg) translate(7.92px,0);transform:rotate(120deg) translate(7.92px,0)}.weui_loading_leaf_5{-webkit-animation:opacity-60-25-5-12 1.25s linear infinite;animation:opacity-60-25-5-12 1.25s linear infinite}.weui_loading_leaf_5:before{-webkit-transform:rotate(150deg) translate(7.92px,0);transform:rotate(150deg) translate(7.92px,0)}.weui_loading_leaf_6{-webkit-animation:opacity-60-25-6-12 1.25s linear infinite;animation:opacity-60-25-6-12 1.25s linear infinite}.weui_loading_leaf_6:before{-webkit-transform:rotate(180deg) translate(7.92px,0);transform:rotate(180deg) translate(7.92px,0)}.weui_loading_leaf_7{-webkit-animation:opacity-60-25-7-12 1.25s linear infinite;animation:opacity-60-25-7-12 1.25s linear infinite}.weui_loading_leaf_7:before{-webkit-transform:rotate(210deg) translate(7.92px,0);transform:rotate(210deg) translate(7.92px,0)}.weui_loading_leaf_8{-webkit-animation:opacity-60-25-8-12 1.25s linear infinite;animation:opacity-60-25-8-12 1.25s linear infinite}.weui_loading_leaf_8:before{-webkit-transform:rotate(240deg) translate(7.92px,0);transform:rotate(240deg) translate(7.92px,0)}.weui_loading_leaf_9{-webkit-animation:opacity-60-25-9-12 1.25s linear infinite;animation:opacity-60-25-9-12 1.25s linear infinite}.weui_loading_leaf_9:before{-webkit-transform:rotate(270deg) translate(7.92px,0);transform:rotate(270deg) translate(7.92px,0)}.weui_loading_leaf_10{-webkit-animation:opacity-60-25-10-12 1.25s linear infinite;animation:opacity-60-25-10-12 1.25s linear infinite}.weui_loading_leaf_10:before{-webkit-transform:rotate(300deg) translate(7.92px,0);transform:rotate(300deg) translate(7.92px,0)}.weui_loading_leaf_11{-webkit-animation:opacity-60-25-11-12 1.25s linear infinite;animation:opacity-60-25-11-12 1.25s linear infinite}.weui_loading_leaf_11:before{-webkit-transform:rotate(330deg) translate(7.92px,0);transform:rotate(330deg) translate(7.92px,0)}@-webkit-keyframes opacity-60-25-0-12{0%{opacity:.25}0.01%{opacity:.25}0.02%{opacity:1}60.01%{opacity:.25}100%{opacity:.25}}@-webkit-keyframes opacity-60-25-1-12{0%{opacity:.25}8.34333%{opacity:.25}8.35333%{opacity:1}68.3433%{opacity:.25}100%{opacity:.25}}@-webkit-keyframes opacity-60-25-2-12{0%{opacity:.25}16.6767%{opacity:.25}16.6867%{opacity:1}76.6767%{opacity:.25}100%{opacity:.25}}@-webkit-keyframes opacity-60-25-3-12{0%{opacity:.25}25.01%{opacity:.25}25.02%{opacity:1}85.01%{opacity:.25}100%{opacity:.25}}@-webkit-keyframes opacity-60-25-4-12{0%{opacity:.25}33.3433%{opacity:.25}33.3533%{opacity:1}93.3433%{opacity:.25}100%{opacity:.25}}@-webkit-keyframes opacity-60-25-5-12{0%{opacity:.270958333333333}41.6767%{opacity:.25}41.6867%{opacity:1}1.67667%{opacity:.25}100%{opacity:.270958333333333}}@-webkit-keyframes opacity-60-25-6-12{0%{opacity:.375125}50.01%{opacity:.25}50.02%{opacity:1}10.01%{opacity:.25}100%{opacity:.375125}}@-webkit-keyframes opacity-60-25-7-12{0%{opacity:.479291666666667}58.3433%{opacity:.25}58.3533%{opacity:1}18.3433%{opacity:.25}100%{opacity:.479291666666667}}@-webkit-keyframes opacity-60-25-8-12{0%{opacity:.583458333333333}66.6767%{opacity:.25}66.6867%{opacity:1}26.6767%{opacity:.25}100%{opacity:.583458333333333}}@-webkit-keyframes opacity-60-25-9-12{0%{opacity:.687625}75.01%{opacity:.25}75.02%{opacity:1}35.01%{opacity:.25}100%{opacity:.687625}}@-webkit-keyframes opacity-60-25-10-12{0%{opacity:.791791666666667}83.3433%{opacity:.25}83.3533%{opacity:1}43.3433%{opacity:.25}100%{opacity:.791791666666667}}@-webkit-keyframes opacity-60-25-11-12{0%{opacity:.895958333333333}91.6767%{opacity:.25}91.6867%{opacity:1}51.6767%{opacity:.25}100%{opacity:.895958333333333}}</style>';
            _html += _style
        }
        if ($("#ks-loadingToast").length > 0) {
            $("#ks-loadingToast").show()
        } else {
            $("body").append(_html)
        }
    }

    KSSPA.prototype.hideLoading=function() {
        $("#ks-loadingToast").hide()
    }

    function startRouter() {
        var hash = location.hash;
        var routeObj = ksspa.parse(hash);
        routerAction(routeObj)
    }

    function loadScript(src, callback) {

        if ($('script[src="' + src + '"]').length > 0) {
            return false;
        }
        var script = document.createElement('script'),
            loaded;
        script.setAttribute('src', src);
        script.onreadystatechange = script.onload = function () {
            script.onreadystatechange = null;
            document.documentElement.removeChild(script);
            script = null;
            if (!loaded) {
                if (typeof callback === 'function')
                    callback()
            }
            loaded = true
        };
        document.documentElement.appendChild(script)
    }


    KSSPA.prototype.close = function ($routers) {
        if ($routers != '') {
            var array = $routers.split(',');
            for (index in array) {
                var id = '#ks-' + array[index];
                $(id).remove();
            }
            history.go(-1);
        }
    }

    ksspa = new KSSPA();

    return ksspa;

})